package com.hua.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hua.error.CustomException;
import com.hua.mapper.BlogMapper;
import com.hua.pojo.Blog;
import com.hua.pojo.BlogCategory;
import com.hua.pojo.Comment;
import com.hua.pojo.User;
import com.hua.service.BlogCategoryService;
import com.hua.service.BlogService;
import com.hua.service.UserService;
import com.hua.utils.HuaUtil;
import com.hua.vo.ArticleData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author ONE-X
 * @date 2020/11/10
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {
	@Autowired
	private BlogService blogService;
	@Autowired
	private BlogMapper blogMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private BlogCategoryService blogCategoryService;
	@Override
	public Integer findBlogByAuthorCount(String authorID) {
		return blogService.count(new QueryWrapper<Blog>().eq("author_id",authorID));
	}

	@Override
	public IPage<Blog> findAllBlog(IPage<Blog> iPage, String categoryName, String uid) {
		QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
		// 进行排序
		blogQueryWrapper.orderByDesc("gmt_create");
		if(!(categoryName == null || "".equals(categoryName))){
			blogQueryWrapper.eq("category_name",categoryName);
		}
		if(!(uid == null || "".equals(uid))){
			blogQueryWrapper.eq("author_id",uid);
		}
		iPage = blogMapper.selectPage(iPage,blogQueryWrapper);
		return iPage;
	}

	@Override
	public void addBlog(ArticleData articleData) {
		// 获取当前用户信息
		User user = userService.getOne(new QueryWrapper<User>().eq("uid", HuaUtil.returnAuthentication()));
		if(user == null){
			throw new CustomException("没有获取当前用户信息");
		}
		// 获取博客类型的信息
		BlogCategory category = blogCategoryService.getOne(new QueryWrapper<BlogCategory>().eq("category", articleData.getCategory()));
		if(category == null){
			throw new CustomException("没有获取当前用户信息");
		}
		Blog blog = new Blog(0
				,HuaUtil.getUuid()
				,articleData.getTitle()
				,articleData.getText()
				,0
				,0
				,user.getUid()
				,user.getUsername()
				,user.getAvatar()
				,category.getId()
				,category.getCategory()
				,new Date()
				,new Date()

		);
		// 开始插入数据
		blogService.save(blog);
	}



}
